function G(itm){var element=document.getElementById(itm);if(!element){element=document.getElementsByName(itm)[0]}return element}
function autoCheckbox(itm,val,s){var o=document.getElementsByName(itm);if(!o) return;s=s||',';var vals=val.split(s);for(var s=0;s<vals.length;s++){for(i=0;i<o.length;i++){if(o[i].value==trim(vals[s])){o[i].checked=true;break}}}}
function autoRadio(itm,val){var o=document.getElementsByName(itm);if(!o) return;for(var i=0;i<o.length;i++){if(o[i].value==val){o[i].checked=true;break}}}
function autoInput(itm,val){var o=G(itm);if(!o) return;o.value=val}
function autoSelect(itm,val){var o=G(itm);if(!o) return;for(i=0;i<o.options.length;i++){if(o.options[i].value==val){o.selectedIndex=i;break}}}
function addoptions(obj,text,val){var o=G(obj);if(!o) return;var opt=document.createElement('OPTION');opt.text=text;opt.value=val;o.options.add(opt,o.length)}
function getCheckboxItem(itm){var allSel='';var o=document.getElementsByName(itm);if(!o) return allSel;for(i=0;i<o.length;i++){if(o[i].checked){allSel=allSel==''?o[i].value:allSel+','+o[i].value}}return allSel}
function trim(str){return str.replace(/(^\s*)|(\s*$)/g,'')}
function choose(sel, id){$(sel).bind('click', function() {$("input[name='"+ id +"']").prop("checked", this.checked);});	}
//获取location的请求参数
function reqParam(name) {var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");var r = window.location.search.substr(1).match(reg);if (r != null) return unescape(r[2]);return null;}
/**
 * 获取当前的iframe弹出层
 * @returns {Window|*|null}
 */
function getCurrentLayer(idx) {
    var winLength = $(top.document).find(".layui-layer-iframe").length
    console.log("open win ", winLength)
    //只打开一层的时候 直接返回top
    if ( winLength == 1 ) {
        console.log("return top")
        return top;
    }
    var module_id = $("#module_id").val();
    console.log('module_id',module_id,idx);

    if ( typeof module_id == "undefined" || typeof top.window.mod == "undefined" || typeof top.window.mod[module_id] == "undefined" ) {
        if ( typeof idx == "undefined" || idx==='' ) {
            return top;
        }
    }

    var layuiIframe = idx?top.document.getElementById("layui-layer-iframe" + idx):(module_id ? top.document.getElementById("layui-layer-iframe" + top.window.mod[module_id]) : "");

    if ( layuiIframe && typeof layuiIframe.contentWindow !== "undefined") {
        var _parent = layuiIframe.contentWindow;
    } else {
        var _parent = top;
    }
    return _parent;
}

//删除提示
function del(){
	if(window.confirm('你确定要删除吗?')) return true;
	else return false;
}
//弹窗 引用layer
function win(options, layer){
    layer = layer||top.layer;
	options.title = options.title || false;
	options.w = options.w || '700px';
	options.h = options.h || '420px';
	options.maxmin  = options.maxmin || false;
	options.cancel = options.cancel || function(index, layero){};
	options.succ = options.succ || function(layero, index){};
    options.end = options.end || null;
	options.yes = options.yes || function(index, layero){layer.close(index);};
	options.btn = options.btn || false;

	var area = 'auto';
	if(options.w!='auto'&&options.h=='auto')
		area = options.w;
	else if(options.w!='auto'&&options.h!='auto')
		area = [options.w, options.h];

	if(options.shade==undefined) options.shade = 0.8;
	if(options.shadeClose==undefined) options.shadeClose = true;

	if(options.scroll==undefined) options.scroll = true;
	if(options.close==undefined) options.close = 1;
	
	if(options.url==undefined || options.url=='') return;
    layer.open({
	  type: 2, title: options.title, scrollbar:options.scroll, shadeClose: options.shadeClose, shade: options.shade, area: area, maxmin: options.maxmin, content: options.url, cancel: options.cancel, success: options.succ, restore: options.succ, yes: options.yes, btn: options.btn, closeBtn: options.close, end:options.end
	});
}
//iframe页面关闭自身时
function close_win(func){
	//javascript:top.window.history.go(0);//reload();
	var index = top.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    console.log(index);
	typeof(func)=="function" && func(); //执行回调
	top.layer.close(index);
}
function ifr_reload(name){ //ifr重新刷新载入
	if(top.frames[name==undefined?"main":name]==undefined) top.location.reload();
	else top.frames[name==undefined?"main":name].location.reload();
}
function error_msg(info, func){
    top.layer.msg(info, {shade:0.5,shadeClose:true,icon:2,end:function(){
        if(typeof(func)=="function")
            func();
    } });  
}
function success_msg(info, func){
    top.layer.msg(info, {time:2000,shade:0.5,shadeClose:true,icon:1,end:function(){
        if(typeof(func)=="function")
            func();
    } });  
}
//html弹窗 传入元素 #id或.class, 回调方法 传入弹窗index及弹窗对象
function pop_html(id, opt){ //succ, yes
	opt = opt==undefined?{}:opt;
	var index = layer.open({
		title: opt.title==undefined?false:opt.title,
  		closeBtn: 0,
  		area: opt.width==undefined?'auto':opt.width,
		content: id?$(id).html():opt['content'],
		btn: ['确定', '取消'],
		success: function(layero, index){
			typeof opt.succ === "function" && opt.succ(layero, index);
		},
		yes: function(index, layero){
			typeof opt.yes === "function" && opt.yes(layero, index);
			layer.close(index);
  		},
  		cancel: function(index, layero){ 
			typeof opt.cancel === "function" && opt.cancel(layero, index);
			layer.close(index);
		},
        end:function(){
            typeof opt.end === "function" && opt.end();
        }
	});
}
//重置alert 引用layer
function alert(msg,func){
	//top.layer.config({});
    top.layer.alert(msg.replace(/\n/g,'<br>'), {
      icon: 3,
	  title:false,
	  closeBtn:0
    }, function(index){
      	typeof(func)=='function' && func();
		top.layer.close(index);
	}); 
}

//表格:增加行|删除行 扩展
(function($){
	//批量给select设置option {json} name=val
	$.fn.setSelect = function(opts,s){
		if(typeof(opts)!='object') return;
		var v,i,n,opt, o=$(this), kv = opts.length==undefined?true:false; //是键值还是数组
		s = s||'='; //分隔符
		//console.log(opts);
		for(n=0;n<o.length;n++){
			for(i in opts){
				opt=document.createElement('OPTION');
				if(kv){
					opt.text = i;opt.value = opts[i];
				}else{
					v = opts[i].split(s);
					opt.text = v[0];
					opt.value = (v[1]==undefined?v[0]:v[1]);
				}
				o[n].options.add(opt,o[n].length);
			}
		}
	};
	//公开的 规则，模式[1,2,3] 模式3中msgtype为false时仅输入第一个错误
	$.fn.tb_add_del = function(options) { 
		var opt = {
			len:8, //限制行数
			tplself:false, //是否复制自身
			trhead:'<tr>', //tr开头标识
			istr:true, //模板tr行是在表格tbody里
			tpl:'#__rowtpl', //行模板标签 id或类名 模板内容不包含tr标签
			tbody:'tbody', //增加行时的容器 id,类名或标签名
			del:'.__rowdel', //删除行元素标识 tr>td>元素标识
			add:'.__rowadd', //增加行元素标识 
			alert:function(msg){
				alert(msg);
			},
			addfun:function(tr){
				//点击增加按钮后的处理
			}
		};
		opt = $.extend(opt,options);
		//console.log(opt);
		
		var tbox = $(this); //表格容器
		var tbody = tbox.find(opt.tbody);
		var html = '';
		if(opt.tplself){
			$(opt.tpl).show();
			html = $(opt.tpl).prop("outerHTML");
		}else{
			html = opt.istr ? opt.trhead+$(opt.tpl).html()+'</tr>' : $(opt.tpl).html();
		}
		//var html = opt.tplself?$(opt.tpl).prop("outerHTML"):opt.trhead+$(opt.tpl).html()+'</tr>';
		$(opt.tpl).hide();
		//console.log(html);
		tbox.on('click',opt.del+','+opt.add,function(){
			var tr_len = tbox.find(opt.tbody+'>tr').length-(opt.istr?1:0);
			if($(this).filter(opt.del).length>0){ //删除
				$(this).parent().parent().remove();
			}else if($(this).filter(opt.add).length>0){ //添加 最多设置opt.len个
				if(opt.len==tr_len){
					opt.alert("最多只可设置"+opt.len+"行数据");
					return false;
				}
				tbody.append(html);
				opt.addfun(tbody.find('tr:last'));
			}
			return false;
		});
	}
})(jQuery);

var STATIC_URL = 'https://static.guanliyuangong.com';
//h5 audio 播放
var h5_audio = {
    init:function(){
        var h5Audio = {
            audio:null,
            audios:null,
            hasplay:false,
            timer:null, //定时
            delay:0,
            init:function(){
                if(this.audio) return;
                this.audio = new Audio();
                this.audio.preload = true;
                this.audio.controls = true;
                this.audio.loop = false;//禁止循环，否则无法触发ended事件
            },
            play:function(audios){
                this.init();
                if(audios!=undefined) {
                    this.audios = audios;
                    this.audio.addEventListener('ended', this.playEndedHandler, false);
                }
                //console.log(this.audios);
                if(this.audios.length==0) {return;}
                this.hasplay = true;
                var src = this.audios.shift(); //每次读数组第一个元素
                if(typeof(src)=='number'){ //有延迟 加有延迟播放毫秒
                    this.timer = setTimeout(function(){
                        h5Audio.play();
                    }, src);
                }else{
                    this.audio.src = src;
                    this.audio.play();
                    if(!h5Audio.audios.length) this.hasplay=false;
                }
            },
            playEndedHandler:function(){
                //console.log(h5Audio.audio.src);
                setTimeout(function(){h5Audio.play()}, h5Audio.delay);
                !h5Audio.audios.length && h5Audio.audio.removeEventListener('ended', h5Audio.playEndedHandler, true);//只有一个元素时解除绑定
            },
            pause:function(){
                clearTimeout(this.timer);
                this.audio.pause();
            },
            setVol:function(vol){
                if(vol>1) vol=1;
                if(vol<0) vol=0;
                this.audio.volume=vol;
            },
            getVol:function(){
                return this.audio.volume;
            }
        };
        h5Audio.init();
        return h5Audio;
    }
};

var voice = {
    music_json:null, //非真人音
    zhenr_json:null, //真人音
    vars:{
        "{#来源座号}":"十,二",
        "{#目标座号}":"二,十",
        "{#预告时间}":"十,二,点,三,十",
        "{#中奖名额}":"六",
        "{#活动任务}":"杀敌数,满,一,百",
        "{#LOL大区}":"德玛西亚",
        "{#LOL段位}":"黄金",
        "{#商户属名}":"本店"
    },
    listen:STATIC_URL+'/voice/md5_',
    listen_diy:STATIC_URL+'/0/1/voice/',
    audio_theme:'xiaowei', //语音主题
    yyArr:[],
    h5Audio:null,
    bgMyAudio:null,
    bgmFlag:false,
    bgm_t:null,
    opt:null,
    init:function( theme, vars){ //语音主题 变量配置
        if(theme!=undefined) this.audio_theme = theme;
        if(vars!=undefined) this.vars = $.extend(this.vars, vars);

        if(voice.zhenr_json==null){
            $.getJSON(STATIC_URL+"/voice/md5_"+ voice.audio_theme +".json",function(data){
                voice.zhenr_json = data;
            });
            $.getJSON(STATIC_URL+"/voice/md5_music.json",function(data){
                voice.music_json = data;
            });
            $.getJSON(STATIC_URL+"/voice/glob.json",function(data){
                var j, re, k, vars = voice.vars; //JSON.parse(JSON.stringify(voice.vars));

                    for(var i in data){
                        k = Math.floor(Math.random()*data[i].length);
                        for(j in vars){
                            re = new RegExp(j,"g");
                            data[i][k] = (data[i][k]).replace(re, ','+voice.vars[j]+',');
                        }
                        //console.log(k);
                        voice.vars['{#'+ i +'}'] = data[i][k];
                    }
                    //console.log(vars);
                //console.log(voice.vars);
            });
            voice.h5Audio = h5_audio.init();
        }
    },
    set_var:function(k,v){
        this.vars[k] = v;
    },
    set_opt:function(opt){
        if(this.opt) return;
        opt = opt || {};
        opt.ele = opt.ele || '.__shiting'; //选择元素
        opt.flag_on = opt.flag_on || '__play'; //试听样式标识
        opt.flag_off = opt.flag_off || '__stop'; //停止样式标识
        opt.i_flag_on = opt.i_flag_on || 'fa-play-circle-o'; //试听i 样式标识
        opt.i_flag_off = opt.i_flag_off || 'fa-pause-circle-o'; //停止i 样式标识

        opt.__on = function(el){
            $(opt.ele).addClass(opt.flag_on).removeClass(opt.flag_off);
            $(opt.ele).find('i').addClass(opt.i_flag_on).removeClass(opt.i_flag_off);

            el.addClass(opt.flag_off).removeClass(opt.flag_on);
            el.find('i').addClass(opt.i_flag_off).removeClass(opt.i_flag_on);
        };
        opt.play_on = opt.play_on || function(el){ //点击播放处理
            $(opt.ele).each(function(){
                $(this).html($(this).html().replace('试听',$(this).data('startname')||'试听'));
            });
            el.html(el.html().replace('停止',el.data('stopname')||'停止'));
        };
        opt.__off = function(el){
            el.addClass(opt.flag_on).removeClass(opt.flag_off);
            el.find('i').addClass(opt.i_flag_on).removeClass(opt.i_flag_off);
        };
        opt.play_off = opt.play_off || function(el){ //点击停止处理
            el.html(el.html().replace('试听',el.data('startname')||'试听'));
        };
        opt.play_end = opt.play_end || opt.play_off; //播放结束处理
        this.opt = opt;
    },
    setAudArr:function(txt, bool){
        var audList=[], arr_t, i, v, hasfind=false, p=false, txt2;bool = bool||false; //是否直接返回组合数组
        if(txt=='') return bool ? audList : false;

        for(var j in voice.vars){ //模板变量处理
            if(txt.indexOf(j)!=-1){
                var re = new RegExp(j,"g");
                txt = txt.replace(re, ','+voice.vars[j]+','); ///{#商户属名}/g
            }
        }
        for(var j in voice.vars){ //模板变量二次处理
            if(txt.indexOf(j)!=-1){
                var re = new RegExp(j,"g");
                txt = txt.replace(re, ','+voice.vars[j]+','); ///{#商户属名}/g
            }
        }
        //txt = txt.replace(/,,/g, ',');
        console.log(txt);
        arr_t = txt.split(',');
        while(undefined!=(i=arr_t.shift())){
            txt = i;
            if(txt=='') continue;

            var inter = txt.match(/{#(\d{3,5})}/);   // 尝试去匹配搜索字符串。
            if(inter){ //延迟
                inter[1] = parseInt(inter[1]);
                if(!isNaN(inter[1])) bool ? audList.push(inter[1]) : voice.yyArr.push(inter[1]);
            }
            txt = txt.replace(/{#[^}]*?}/g, ''); //清除无效变量

            hasfind = false;
            if(txt.substr(0,4)=='http'){ //直接mp3地址
                bool ? audList.push(txt) : voice.yyArr.push(txt);
            }else{
                p = txt.lastIndexOf('|music');
                if(p!=-1){ //非真人音
                    p = txt.lastIndexOf('|music');
                    txt = txt.substr(0,p);
                    txt2 = txt.replace(/[\[\]_\(\)]/g,'');
                    v = voice.music_json[txt] || voice.music_json[txt2] || false;
                    if(v){
                        bool ? audList.push(voice.listen+'music/' + v) : voice.yyArr.push(voice.listen+'music/' + v);
                    }
                }else{ //真人音
                    v = voice.zhenr_json[txt] || false;
                    if(v){
                        bool ? audList.push(voice.listen+voice.audio_theme+'/' + v) : voice.yyArr.push(voice.listen+voice.audio_theme+'/' + v);
                    }
                }
            }
            console.log(txt,v);
        }
        console.log(audList);
        return bool ? audList : true;
    },
    ele_play:function(el){
        if(!this.opt) this.set_opt();
        var arr_t, i;
        var listen=this.listen, opt = this.opt;
        voice.yyArr = [];
        if(voice.bgMyAudio){
            voice.bgMyAudio.pause(); //如果有背景音 停止
            clearInterval(voice.bgm_t);
            voice.bgm_t = null;
        }

        if(el.hasClass(opt.flag_on) || !el.hasClass(opt.flag_off)){
            opt.play_on(el); opt.__on(el);
            // delay : 100,200,0 前 中 后
            var delay=parseInt(el.attr('data-delay')), bgmvol=parseInt(el.attr('data-bgmvol')),
                bgm = el.attr('data-bgm_id')?$('#'+el.attr('data-bgm_id')).val():(el.attr('data-bgm') || ''),
                hint = el.attr('data-hint_id')?$('#'+el.attr('data-hint_id')).val():(el.attr('data-hint') || ''),
                pre = el.attr('data-pre_id')?$('#'+el.attr('data-pre_id')).val():(el.attr('data-pre') || ''),
                suf = el.attr('data-suf_id')?$('#'+el.attr('data-suf_id')).val():(el.attr('data-suf') || ''),
                af = el.attr('data-af_id')?$('#'+el.attr('data-af_id')).val():(el.attr('data-af') || ''),
                mp3 = el.attr('data-mp3'), el_var = el.find('var').text();
            if(el_var){
                el_var = JSON.parse(el_var);
                for(i in el_var){
                    this.set_var('{#'+i+'}', el_var[i]);
                }
                //console.log('var',this.vars);
            }
            //console.log('el_var',el_var);
            //console.log(el.data('bgm_id'),el.data('hint_id'),$('#'+el.data('hint_id')).val(),hint);
            //临时切换
            var tmpTheme = null, theme = el.attr('data-theme');
            if(theme && theme!=voice.audio_theme) {
                tmpTheme = voice.audio_theme;
                voice.init(theme);
            }

            if(bgm!='' && voice.bgMyAudio==null){ //初始背景音
                voice.bgMyAudio = h5_audio.init();
            }
            //提示音
            if(hint!=''){
                if(bgm!='') bgm = hint+','+bgm;
                else voice.setAudArr(hint);
            }
            //前缀
            voice.setAudArr(pre);
            //语音主体
            if(mp3!=undefined){ //直接mp3
                arr_t = mp3.split(',');
                while(i=arr_t.shift()){
                    voice.yyArr.push(listen+voice.audio_theme+'audio/' + i);
                }
            }else{
                var type = el.data('type');
                var txt = el.data('txt')||'';

                if(type=='diy'){ //自定义语音
                    voice.yyArr.push(voice.listen_diy+el.data('diy'));
                }else{
                    voice.setAudArr(txt);
                }
            }
            console.log(af);
            //语音主体之后
            voice.setAudArr(af);
            //后缀
            voice.setAudArr(suf);

            //console.log('voice.yyArr', voice.yyArr);

            //背景音
            if(bgm!=''){
                if(isNaN(bgmvol) || bgmvol<0 || bgmvol>100) bgmvol = 90;
                voice.bgMyAudio.setVol(bgmvol/100);
                voice.bgMyAudio.play(voice.setAudArr(bgm, true));
                voice.bgMyAudio.audio.onended = voice.bgMyAudio.audio.onpause = function(){
                    if(!voice.h5Audio.hasplay && !voice.bgMyAudio.hasplay) {opt.play_end(el);opt.__off(el);}
                }
            }
            voice.bgmFlag=false;
            voice.h5Audio.pause();
            if(delay>0){ //有延迟
                setTimeout(function(){
                    voice._aud_todo(el, opt); //播放主要语音
                    if(bgm!='') voice.bgmFlag=true;
                }, delay);
            }else{
                voice._aud_todo(el, opt); //播放主要语音
                if(bgm!='') voice.bgmFlag=true;
            }
            //临时切换还原
            if(tmpTheme) {
                voice.init(tmpTheme);
            }
        }else{
            voice.h5Audio.pause();
            opt.play_off(el);opt.__off(el);
        }
    },
    _aud_todo:function(el, opt){ //播放
        var interval = 0;
        //console.log(voice.yyArr);
        voice.h5Audio.play(voice.yyArr);
        voice.h5Audio.audio.onended = voice.h5Audio.audio.onpause = function(){
            var bgm = voice.bgMyAudio && voice.bgmFlag ? voice.bgMyAudio.audio.ended : true;
            if(!voice.h5Audio.hasplay && voice.bgMyAudio && voice.bgmFlag){
                //console.log(voice.bgm_t);
                if(!voice.bgm_t){
                    //console.log(interval);
                    voice.bgm_t = setInterval(function(){
                        interval++;
                        //console.log(voice.bgMyAudio.getVol()*0.9);
                        voice.bgMyAudio.setVol(voice.bgMyAudio.getVol()*0.8);
                        if(interval>=15){
                            voice.bgMyAudio.pause();
                            clearInterval(voice.bgm_t); //console.log('clear:'+voice.bgm_t);
                            voice.bgm_t = null;
                        }
                    },200);
                }
                /*
                voice.bgMyAudio.setVol(voice.bgMyAudio.getVol()*0.8);
                voice.bgm_t = setTimeout(function(){
                    voice.bgMyAudio.setVol(voice.bgMyAudio.getVol()*0.6);
                    voice.bgMyAudio.pause();
                },3000);*/
            }
            console.log(voice.h5Audio.hasplay, bgm);
            if(!voice.h5Audio.hasplay && bgm) {opt.play_end(el);opt.__off(el);}
        };
    },
    run:function(opt){ //执行监听
        this.set_opt(opt);
        //试听与暂停切换
        $(this.opt.ele).on('click', function(){
            var el = $(this);
            voice.ele_play(el);
            return false;
        });
    },
    play:function(txt){ //手动触发 仅播放
        var arr_t, i, h5Audio=voice.h5Audio;
        voice.yyArr = [];
        txt = txt || '';
        h5Audio.pause();
        if(voice.bgMyAudio){
            voice.bgMyAudio.pause(); //如果有背景音 停止
            clearInterval(voice.bgm_t);
            voice.bgm_t = null;
        }
        if(voice.opt){
            var el = $(voice.opt.ele).filter('.'+voice.opt.flag_off);
            if(el.length){
                //console.log(el.data('startname'));
                voice.opt.play_off(el);voice.opt.__off(el);
            }
        }
        if(txt.indexOf(',')!=-1){
            arr_t = txt.split(',');
            while(i=arr_t.shift()){ voice.setAudArr(i); }
        }else{
            voice.setAudArr(txt);
        }
        //console.log(voice.yyArr);
        h5Audio.play(voice.yyArr);
    }
};
//cookie
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};